package com.avic.rong.wedgit.customView;

import android.content.Context;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.ActionBar;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.avic.rong.BaseActivity;
import com.avic.rong.R;
import com.avic.rong.bean.product.BookAttrBean;
import com.avic.rong.bean.product.BookCatBean;
import com.avic.rong.bean.product.GoodAttrBean;
import com.avic.rong.goodsSort.api.BookAttrsApi;
import com.avic.rong.utils.ConstantsUtils;
import com.avic.rong.utils.DateUtils;
import com.avic.rong.utils.StringUtils;
import com.avic.rong.utils.ToastTools;
import com.example.minato.minastore.BaseResultEntity;
import com.example.minato.minastore.http.HttpManager;
import com.example.minato.minastore.listener.HttpOnNextListener;
import com.orhanobut.logger.Logger;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Creater: Created by wangyz on 2019/9/6.
 * Email: 936804097@qq.com
 */
public class BookAttrFragment extends Fragment implements View.OnClickListener {


    private Context mContext;


    @BindView(R.id.recycler_list_attrs)
    RecyclerView recycler_list_attrs;//文本基本属性显示

    public List<ItemSearchBean> itemSearchBeanList = new ArrayList<>();
    private SearchGroupAdapter searchGroupAdapter;

    private PopupWindow popupWindow;
    @BindView(R.id.book_drawer)
    RelativeLayout book_drawer;

    private RecyclerView recycler_book_publish;
    private BookPublishItemAdapter publishItemAdapter;

    private View view_left;
    //图书出版社集合
    private List<ItemSearchBean.SubBean> bookPublishList;
    private static final int PUBLISHATTRID = 95;
    private int catIdSelected;

    private View popupWindowView;

    public static BookAttrFragment getInstance(Context context,String catId) {
        BookAttrFragment fragment = new BookAttrFragment();
        fragment.mContext = context;
        if (!StringUtils.isEmpty(catId)){
            fragment.catIdSelected = Integer.parseInt(catId);
        }
        return fragment;
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = LayoutInflater.from(mContext).inflate(R.layout.drawer_book, container, false);
        ButterKnife.bind(this, view);


        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(mContext);
        searchGroupAdapter = new SearchGroupAdapter(mContext);
        recycler_list_attrs.setLayoutManager(linearLayoutManager);
        recycler_list_attrs.setAdapter(searchGroupAdapter);
        BookAttrsApi bookAttrsApi = new BookAttrsApi((BaseActivity) mContext, bookAttrsListener);
        HttpManager.getInstance().doHttpDeal(bookAttrsApi);


        popupWindowView = LayoutInflater.from(mContext).inflate(R.layout.drawer_book_publish, container, false);
        recycler_book_publish = popupWindowView.findViewById(R.id.recycler_book_publish);

        //出版社popwindow初始化
        popupWindowView.findViewById(R.id.tv_clear_popwindow).setOnClickListener(this);
        popupWindowView.findViewById(R.id.tv_ok_popwindow).setOnClickListener(this);
        view_left = popupWindowView.findViewById(R.id.ll_publish_back);
        view_left.setOnClickListener(this);

        publishItemAdapter = new BookPublishItemAdapter(mContext);
        publishItemAdapter.setPopWindowTextView((TextView) popupWindowView.findViewById(R.id.tv_show_select_publish));
        LinearLayoutManager linearLayoutManager2 = new LinearLayoutManager(mContext);
        DividerItemDecoration divider = new DividerItemDecoration(mContext, DividerItemDecoration.VERTICAL);
        divider.setDrawable(ContextCompat.getDrawable(mContext, R.drawable.divider_05_pix));
        recycler_book_publish.addItemDecoration(divider);
        recycler_book_publish.setLayoutManager(linearLayoutManager2);
        recycler_book_publish.setAdapter(publishItemAdapter);

        return view;
    }


    @OnClick({R.id.tv_clear, R.id.tv_ok})
    public void clickOperation(View view) {
        int viewId = view.getId();
        if(DateUtils.isFastDoubleClick()) return;

        switch (viewId) {
            case R.id.tv_ok://确定
                String attrPro = "";
                for (ItemSearchBean searchBean : itemSearchBeanList) {
                    if (SearchGroupAdapter.TYPE_SELECT == searchBean.getControlType()) {
                        if (!StringUtils.isEmpty(searchBean.getValue())) {
                            if (searchBean.getId() == 10000){
                                attrPro = attrPro + "&" + searchBean.getId() + "++" + searchBean.getIdValue() + "__" + searchBean.getValue();
                            }else{
                                attrPro = attrPro + "&" + searchBean.getId() + "__" + searchBean.getValue();
                            }
                        }
                    } else if (SearchGroupAdapter.TYPE_TIME == searchBean.getControlType()) {
                        String stardTime = "";
                        String endTime = "";
                        if (!StringUtils.isEmpty(searchBean.getValue())) {
                            endTime = DateUtils.getFormatShort(System.currentTimeMillis(),DateUtils.FORMAT_SHORT_CN);
                            if (ConstantsUtils.TIME_ONE_MONTH.equalsIgnoreCase(searchBean.getValue())) {
                                stardTime = DateUtils.getBeforeDateShort(30);
                            } else if (ConstantsUtils.TIME_THREE_MONTH.equalsIgnoreCase(searchBean.getValue())) {
                                stardTime = DateUtils.getBeforeDateShort(30 * 3);
                            } else if (ConstantsUtils.TIME_HALF_YEAR.equalsIgnoreCase(searchBean.getValue())) {
                                stardTime = DateUtils.getBeforeDateShort(30 * 6);
                            } else if (ConstantsUtils.TIME_ONE_YEAR.equalsIgnoreCase(searchBean.getValue())) {
                                stardTime = DateUtils.getBeforeDateShort(365);
                            }
                        } else {
                            stardTime = searchBean.getStartTime();
                            endTime = searchBean.getEndTime();
                        }
                        if (!StringUtils.isEmpty(stardTime)) {
                            attrPro = attrPro + "&start" + searchBean.getId() + "__" + stardTime;
                        }
                        if (!StringUtils.isEmpty(endTime)) {
                            attrPro = attrPro + "&end" + searchBean.getId() + "__" + endTime;
                        }
                    } else {
                        if (!StringUtils.isEmpty(searchBean.getValue())) {
                            attrPro = attrPro + "&" + searchBean.getId() + "__" + searchBean.getValue();
                        }
                    }
                }
                Logger.i("-------------------------------" + attrPro);
                if (attrPro.length() > 0) {
                    attrPro = attrPro.substring(1);
                }
                Logger.i("--------------------------ff-----" + attrPro);
                if (clickInterface != null) {
                    clickInterface.clickOK(attrPro);
                }
                break;
            case R.id.tv_clear://清空
                for (ItemSearchBean searchBean : itemSearchBeanList) {
                    for (ItemSearchBean.SubBean subBean : searchBean.getSubBeanList()) {
                        subBean.setChecked(false);
                    }
                    searchBean.setValue("");
                }
                searchGroupAdapter.clearData();
                break;
        }

    }


    //图书属性
    HttpOnNextListener<BaseResultEntity> bookAttrsListener = new HttpOnNextListener<BaseResultEntity>() {
        @Override
        public void onNext(BaseResultEntity subjects) {
            if (!ConstantsUtils.STATUS_SUCCESS_200.equals(subjects.getCode())) {
                ToastTools.showToast(mContext, subjects.getMsg());
                return;
            }
            BookAttrBean bookAttrBean = (BookAttrBean) subjects.getData();

            //处理分类
            List<BookCatBean> bookCatList = bookAttrBean.getBookCat();
            ItemSearchBean searchBean = new ItemSearchBean();
            for (BookCatBean catBean : bookCatList) {
                ItemSearchBean.SubBean subBean = new ItemSearchBean.SubBean();
                subBean.setName(catBean.getCatName());
                subBean.setId(catBean.getCatId());
                if (catIdSelected == catBean.getCatId()){////从分类点击跳转回显
                    subBean.setChecked(true);
                    searchBean.setIdValue(String.valueOf(catBean.getCatId()));
                    searchBean.setValue(catBean.getCatName());
                }
                searchBean.getSubBeanList().add(subBean);

            }
            searchBean.setId(10000);
            searchBean.setName("图书分类");
            searchBean.setControlType(SearchGroupAdapter.TYPE_SELECT);
            searchBean.setShowTimeGroupLayout(false);
            searchBean.setMaxCountFold(6);
            itemSearchBeanList.add(searchBean);


            //处理属性
            for (GoodAttrBean goodAttrBean : bookAttrBean.getAllAttrList()) {
                ItemSearchBean itemSearchBean = new ItemSearchBean();
                if (goodAttrBean.getControlType() == SearchGroupAdapter.TYPE_SELECT) {//select控件
                    for (String attrValue : goodAttrBean.getAttrValues()) {
                        ItemSearchBean.SubBean subBean = new ItemSearchBean.SubBean();
                        subBean.setName(attrValue);
                        itemSearchBean.getSubBeanList().add(subBean);
                    }
                    itemSearchBean.setShowTimeGroupLayout(false);
                } else if (goodAttrBean.getControlType() == SearchGroupAdapter.TYPE_TIME) {//时间控件
                    for (int index = 0; index < 4; index++) {
                        ItemSearchBean.SubBean subBean = new ItemSearchBean.SubBean();
                        if (index == 0) {
                            subBean.setName(ConstantsUtils.TIME_ONE_MONTH);
                        } else if (index == 1) {
                            subBean.setName(ConstantsUtils.TIME_THREE_MONTH);
                        } else if (index == 2) {
                            subBean.setName(ConstantsUtils.TIME_HALF_YEAR);
                        } else if (index == 3) {
                            subBean.setName(ConstantsUtils.TIME_ONE_YEAR);
                        }
                        itemSearchBean.getSubBeanList().add(subBean);
                    }
                }
                if (goodAttrBean.getAttrId() == PUBLISHATTRID) {//出版社特设处理
                    for (String attrValue : goodAttrBean.getAttrValues()) {
                        ItemSearchBean.SubBean subBean = new ItemSearchBean.SubBean();
                        if (!StringUtils.isEmpty(attrValue)) {
                            subBean.setName(attrValue.trim());
                        }
                        itemSearchBean.getSubBeanList().add(subBean);
                    }
                    itemSearchBean.setShowTimeGroupLayout(false);
                    itemSearchBean.setControlType(SearchGroupAdapter.TYPE_SELECT);
                    itemSearchBean.setMaxCountFold(6);
                    itemSearchBean.setSpanCount(2);
                    itemSearchBean.setEndMoreShow(true);
                    itemSearchBean.setMultiSelected(true);
                    itemSearchBean.setMoreInterface(new SearchItermAdapter.MoreInterface() {
                        @Override
                        public void moreClick() {
                            showBookPublish(popupWindowView);
                            if (bookPublishList == null) {
                                for (int index = 0; index < itemSearchBeanList.size(); index++) {
                                    if (itemSearchBeanList.get(index).getId() == 95) {
                                        bookPublishList = itemSearchBeanList.get(index).getSubBeanList();
                                    }
                                }
                            }
                            publishItemAdapter.setDataList(bookPublishList);
                            publishItemAdapter.notifyDataSetChanged();
                        }
                    });
                } else {
                    itemSearchBean.setControlType(goodAttrBean.getControlType());
                }
                itemSearchBean.setId(goodAttrBean.getAttrId());
                itemSearchBean.setName(goodAttrBean.getAttrName());

                itemSearchBeanList.add(itemSearchBean);
            }
            searchGroupAdapter.setDataList(itemSearchBeanList);
            searchGroupAdapter.notifyDataSetChanged();
        }

        @Override
        public void onError(final Throwable e) {
            ToastTools.showToast(mContext, e.getMessage());
        }
    };


    public void showBookPublish(View view) {
        popupWindow = new PopupWindow(view, ActionBar.LayoutParams.MATCH_PARENT, ActionBar.LayoutParams.WRAP_CONTENT, true);
       /* // 产生背景变暗效果
        WindowManager.LayoutParams lp = getWindow()
                .getAttributes();
        lp.alpha = 0.4f;
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
        getWindow().setAttributes(lp);*/
        popupWindow.setBackgroundDrawable(new BitmapDrawable());
        popupWindow.setOutsideTouchable(true);
        popupWindow.setTouchable(true);
        popupWindow.setClippingEnabled(false);
        //从上往下弹出动画效果
        popupWindow.setAnimationStyle(R.style.rightPopupAnimation);
        popupWindow.showAtLocation(book_drawer, Gravity.TOP, 0, 0);

    }


    /**
     * popwindow 的click事件
     * @param v
     */
    @Override
    public void onClick(View v) {
        int viewId = v.getId();
        switch (viewId) {
            case R.id.tv_clear_popwindow://popwindow 清空
                if (bookPublishList != null) {
                    for (ItemSearchBean.SubBean subBean : bookPublishList) {
                        subBean.setChecked(false);
                    }
                }
                if (searchGroupAdapter.searchItemViewMap.get(PUBLISHATTRID) != null) {//出版社
                    searchGroupAdapter.searchItemViewMap.get(PUBLISHATTRID).notifyDataChangeShowSelect();
                }
                break;
            case R.id.tv_ok_popwindow://popwindow确定
                if (searchGroupAdapter.searchItemViewMap.get(PUBLISHATTRID) != null) {//出版社
                    searchGroupAdapter.searchItemViewMap.get(PUBLISHATTRID).notifyDataChangeShowSelect();
                }
                break;
        }

        if (popupWindow != null && popupWindow.isShowing()) {
            popupWindow.dismiss();
        }
    }




    private ClickInterface clickInterface;

    public void setClickInterface(ClickInterface clickInterface) {
        this.clickInterface = clickInterface;
    }


    public interface ClickInterface {
        public void clickOK(String attrPro);
    }


}
